package cn.elane.elastic.global.model;

import cn.elane.elastic.global.util.Converter;
import cn.elane.elastic.global.util.PrintUtil;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

public abstract class NameBeanServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Resource
	private HttpServletRequest request;

	protected String getString(String name) {
		return request.getParameter(name);
	}

	protected Integer getInteger(String name) {
		return Converter.toInteger(this.getString(name));
	}

	protected Double getDouble(String name) {
		return Converter.toDouble(this.getString(name));
	}

	protected Date getDate(String name) {
		return Converter.toDate(this.getString(name));
	}

	protected Date getDateTime(String name) {
		return Converter.toDateTime(this.getString(name));
	}

	protected Date getTime(String name) {
		return Converter.toTime(this.getString(name));
	}

	protected String[] getStringArray(String name) {
		return request.getParameterValues(name);
	}

	protected Integer[] getIntegerArray(String name) {
		return Converter.toArray(this.getStringArray(name), Integer.class);
	}

	protected Double[] getDoubleArray(String name) {
		return Converter.toArray(this.getStringArray(name), Double.class);
	}

	protected Date[] getDateArray(String name) {
		return Converter.toArray(this.getStringArray(name), Date.class);
	}

	protected void setAttribute(String name, Object value) {
		request.getSession().setAttribute(name, value);
	}

	protected Object getAttribute(String name) {
		return request.getSession().getAttribute(name);
	}

	protected void dispatcher(HttpServletResponse response, String path) {
		try {
			request.getRequestDispatcher(path).forward(request, response);
		} catch (Exception e) {
			PrintUtil.println(e);
			throw new RuntimeException(e.getMessage());
		}
	}

	protected NameBean getParams() {
		NameBean bean = new NameBean();
		String name;
		String value;
		Object obj;
		for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements(); ) {
			name = e.nextElement();
			value = request.getParameter(name);
			bean.put(name, value);
		}
		for (Enumeration<String> e = request.getAttributeNames(); e.hasMoreElements(); ) {
			name = e.nextElement();
			obj = request.getAttribute(name);
			bean.put(name, obj);
		}
		return bean;
	}

	protected List<NameBean> getBeanList() {
		List<NameBean> list = new ArrayList<>();
		NameBean bean;
		String name;
		String[] value;
		for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements(); ) {
			name = e.nextElement();
			value = request.getParameterValues(name);
			if (value != null) {
				for (int i = 0; i < value.length; i++) {
					try {
						bean = list.get(i);
					} catch (Exception ex) {
						bean = new NameBean();
						list.add(bean);
					}
					bean.put(name, value[i]);
				}
			}
		}
		return list;
	}

	protected String reWrite(String name) {
		String value;
		try {
			value = this.getString(name);
			this.setAttribute(name, value);
			return value;
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		} finally {
			value = null;
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.reWrite("sessionId");
		String temp = this.getString("method");
		if (temp == null || temp.equals("")) {
			temp = request.getRequestURI();
			temp = temp.substring(temp.lastIndexOf("/") + 1);
		}
		try {
			this.getClass().getDeclaredMethod(temp, HttpServletRequest.class, HttpServletResponse.class).invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			super.doPost(request, response);
		}
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected String toJson(List<NameBean> list) {
		StringBuffer sb = new StringBuffer("[");
		if (list != null && list.size() > 0) {
			for (NameBean bean : list) {
				sb.append(bean.toJson()).append(",");
			}
			sb = new StringBuffer(sb.substring(0, sb.length() - 1));
		}
		sb.append("]");
		return sb.toString();
	}

	private void writeMessage(HttpServlet servlet, HttpServletResponse response, StringBuffer message) {
		writeMessage(servlet, request, response, message.toString());
	}

	private void writeMessage(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response, String message) {
		PrintWriter writer;
		try {
			System.out.println(message);
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			writer = response.getWriter();
			writer.println(message);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			PrintUtil.println(e);
			throw new RuntimeException(e.getMessage());
		} finally {
			writer = null;
		}
	}

	protected String attr(String name, String value) {
		return " " + name + "='" + value + "'";
	}

	@Deprecated
	protected Long getStartIndex(Long pageNo, Long pageSize) {
		return (pageNo - 1) * pageSize;
	}

	@Deprecated
	protected Long getPageNo(Long totalPage, String pageNo) {
		return getPageNo(totalPage, Converter.toLong(pageNo, 1L));
	}

	@Deprecated
	protected Long getPageNo(Long totalPage, Long pageNo) {
		if (pageNo <= 0) {
			return 0L;
		}
		if (pageNo >= totalPage) {
			return totalPage;
		}
		return pageNo;
	}

	@Deprecated
	protected Long getTotalPageNo(Long totalRecord, Long pageSize) {
		return totalRecord / pageSize + (totalRecord % pageSize == 0 ? 0 : 1);
	}
}
